package com.chat.provider.invoke;

import com.chat.server.base.InvokeModel;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Auther created by haoteng on 2019/09/09
 */

@Component
public class SpringBeanContent implements ApplicationContextAware {

    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanContent.applicationContext = applicationContext;
    }

    public static <T> T getBean(String beanName) {
        if (applicationContext.containsBean(beanName)) {
            return (T) applicationContext.getBean(beanName);
        } else {
            return null;
        }
    }

    public static <T> Map<String, T> getBeansOfType(Class<T> baseType) {
        return applicationContext.getBeansOfType(baseType);
    }

    public static Object invoke(InvokeModel invokeModel) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class<?> userClass = Class.forName(invokeModel.getInterfaceName());
        String[] array = invokeModel.getInterfaceName().split("\\.");
//        Object o = SpringBeanContent.getBean(array[array.length-1]);
        Object o = SpringBeanContent.getBean("userService");
        Method method = userClass.getMethod(invokeModel.getMethod());
        return method.invoke(o);
    }
}
